package com.example.isoftservice.service.impl;

import com.example.isoftservice.mapper.UserMapper;
import com.example.isoftservice.pojos.User;
import com.example.isoftservice.service.UserService;
import com.example.isoftservice.shiro.token.JwtToken;
import com.example.isoftservice.util.JwtUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    @Cacheable(cacheNames ="user",key="#user+pageNo+pageSize")
    public Map<String, Object> searchUserList(User user,Integer pageNo,Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(pageNo,pageSize);
        List<Map<String, Object>> resultList = userMapper.selectUserList(user);
        PageInfo<Map<String, Object>> listPageInfo = new PageInfo<>(resultList);
        map.put("total",listPageInfo.getTotal());
        map.put("rows",listPageInfo.getList());
        return map;
    }

    @Override
    @Cacheable(cacheNames ="user",key="#userId")
    public User searchUserById(Integer userId) {
        return userMapper.selectUserById(userId);
    }

    //登录业务
    @Override
    public Map<String, Object> login(String username, String password) {
        Map<String,Object> map = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        String jwt = JwtUtils.createJWT(username,"isoft","1",1000*60*30);
        JwtToken jwtToken = new JwtToken(jwt);
        subject.logout();
        if(!subject.isAuthenticated()){
            try{
                subject.login(jwtToken);
                map.put("code",0);
                map.put("msg","登陆成功!");
                map.put("user",userMapper.login(username));
                map.put("jwtToken",jwtToken.getToken());
                return map;

            }
            catch (IncorrectCredentialsException ice){
                System.out.println("------------用户名/密码错误-------------");
                map.put("code",1);
                map.put("msg","您输入的用户名或密码错误!!!");
                return map;

            }
            catch (LockedAccountException lae){
                System.out.println("------------账户已被锁定----------------");
                map.put("code",2);
                map.put("msg","您的账户已被锁定!!!");
                return map;
            }

            catch (UnknownAccountException uae){
                System.out.println("------------未知账户----------------");
                map.put("code",3);
                map.put("msg","未知的账户!!!");
                return map;
            }
            catch (AuthenticationException ae){
                System.out.println("--------------未知错误---------------");
                System.out.println(ae.getMessage());
                map.put("code",4);
                map.put("msg","产生未知的错误!!!");
                return map;
            }
        }
        map.put("code",5);
        map.put("msg","登陆异常,请稍后重试!!!");
        return map;
    }

    @Override
    @CacheEvict(cacheNames = "user" ,allEntries = true)
    public Boolean removeUserByIds(Integer[] ids) {
        return userMapper.deleteUserByIds(ids) >= 1 ? true : false;
    }

    @Override
    public Boolean addUser(User user) {
        user.setCreateTime(new Date(System.currentTimeMillis()));
        user.setUserIcon("https://gss0.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/a2cc7cd98d1001e900e51e21bb0e7bec55e797c6.jpg");
        user.setPassword(md5("123456"+"10086"));
        return userMapper.insertUser(user) == 1 ? true : false;
    }

    @Override
    @CacheEvict(cacheNames = "user" ,allEntries = true)
    public Boolean modifyUserById(User user) {
        return userMapper.updateUserById(user) == 1 ? true : false;
    }

    @Override
    public Boolean modifyUserPassword(User user) {
        User actuallyUser = userMapper.selectUserById(user.getUserId());
        actuallyUser.setPassword(md5(user.getPassword()+ "10086"));
        return userMapper.updateUserPassword(actuallyUser) == 1 ? true : false;
    }

    @Override
    public User getUser(String username) {
        return userMapper.login(username);
    }


    public static String md5(String key){
        if (StringUtils.isBlank(key)){
            return null;
        }
        return DigestUtils.md5DigestAsHex(key.getBytes());
    }
}
